package com.tanhua.server.interceptor;

import com.tanhua.server.pojo.User;
import com.tanhua.server.service.UserService;
import com.tanhua.server.utils.NoAuthorization;
import com.tanhua.server.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName :  TokenInterceptor
 * @Author : Tenebrous
 * @Date: 2020/12/12 21:33
 * @Description : token拦截器
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 清空线程
        UserThreadLocal.set(null);
        // 判断，请求的方法是否包含了NoAuthorization , 如果包含了，就不需要做处理
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            NoAuthorization annotation = handlerMethod.getMethod().getAnnotation(NoAuthorization.class);
            if (annotation != null) {
                return true;
            }
        }

        // 根据头信息获取token
        String token = request.getHeader("Authorization");
        // 根据token获取use信息
        User user = this.userService.queryUserByToken(token);
        if (null == user) {
            // 如果为null，没有访问权限
            response.setStatus(401);
            return false;
        }
        // 存储到当前的线程中
        UserThreadLocal.set(user);
        return true;
    }
}
